package com.hrbxlh.actionImpl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.hrbxlh.dao.SiteDao;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hrbxlh.dao.DepartMentDao;
import com.hrbxlh.util.pageUtil;

@Component("departMentActionImpl")
@Transactional
public class DepartMentActionImpl {
	
	@Resource(name = "departMentDao")
	private DepartMentDao departMentDao;

	@Resource(name = "siteDao")
	private SiteDao siteDao;

	org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(DepartMentActionImpl.class.getName());
	
	/**
	 * @description 获取全部院系信息
	 * @param paramMap  如果有查询条件，就将条件set到map中，
	 *        如果是数据库存在的字段，key值要与column的值相同。
	 * @return List<Map<String,Object>> (院系集合)
	 * @throws Exception
	 */
	public List<Map<String, Object>> getDepartMentList(Map<String, Object> paramMap) throws Exception {

		List<Map<String, Object>> returnList = new ArrayList<Map<String, Object>>();
		try {
			returnList=departMentDao.getDepartMentList(paramMap);
		} catch (Exception e) {
			logger.error("获取全部院系异常getDepartMentList", e);
			throw e;
		}
		return returnList;
	}
	 
	 /**
	 * @description 查询院系列表  分页
	 * @param  paramMap
	 * @return List 
	 * @throws Exception
	 */
	public Map<String,Object> getDepartmentList(Map<String, Object> paramMap) throws Exception{
		
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try{
			int pageNow = Integer.parseInt(paramMap.get("pageNow").toString());
			int pageSize = Integer.parseInt(paramMap.get("pageSize").toString());
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取列表信息
			List<Map<String, Object>> homeworkList = departMentDao.getDepartmentList(paramMap);
			resultMap.put("departmentList", homeworkList);
			resultMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			paramMap.put("startNum", 0);
			List<Map<String, Object>> allList = departMentDao.getDepartmentList(paramMap);
			int totalPage = pageUtil.getTotalPage(allList, pageSize);
			resultMap.put("totalPage", totalPage);
		}catch(Exception e){
			logger.error("查询院系列表异常getDepartmentList", e);
			throw e;
		}
		return resultMap;
	}
	
	 /**
	 * @description 查询全部院系
	 * @param  paramMap Map<String,Object>
	 * @return List 
	 * @throws Exception
	 */
	public List<Map<String,Object>> getDepartmentAll(Map<String, Object> paramMap) throws Exception{
		
		List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
		try{
			resultList = departMentDao.getDepartmentList(paramMap);
		}catch(Exception e){
			logger.error("查询全部院系异常getDepartmentAll", e);
			throw e;
		}
		return resultList;
	}
	
	/**
	 * @description 添加院系
	 * @param  paramMap  院系名称
	 * @return Map<String, String> result true成功，false失败 errorMsg错误信息
	 * @throws Exception
	 */
	public Map<String, Object> addDepartment(Map<String, Object> paramMap) throws Exception {

		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean result = false;
		String failMsg = "";
		try {
//			//1013过滤输入
//			String departmentName = ParamConvertUtil.replaceHTMLCodeOne((String)paramMap.get("departmentName"));
//			paramMap.put("departmentName", departmentName);
			List<Map<String, Object>> departmentList = departMentDao.getDepartmentByName(paramMap);
			//判断院系名重复
			if(departmentList != null && departmentList.size() != 0){
				failMsg = "该院系名已存在";
			}else{
				//添加院系
				departMentDao.addDepartment(paramMap);
				result = true;
			}
			if(!result){
				resultMap.put("failMsg", failMsg);
			}
			resultMap.put("result", result);
			logger.info("添加院系参数为："+paramMap.toString());
		} catch (Exception e) {
			logger.error("添加院系异常addDepartment", e);
			throw e;
		}
		return resultMap;
	}
	
	/**
	 * @description 修改院系
	 * @param  paramMap  院系名称
	 * @return Map<String, String> result true成功，false失败 errorMsg错误信息
	 * @throws Exception
	 */
	public Map<String, Object> saveDepartment(Map<String, Object> paramMap) throws Exception {

		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean result = false;
		String failMsg = "";
		try {
//			//1013过滤用户输入
//			String departmentName = ParamConvertUtil.replaceHTMLCodeOne((String)paramMap.get("departmentName"));
//			paramMap.put("departmentName", departmentName);
			List<Map<String, Object>> departmentList = departMentDao.getDepartmentByName(paramMap);
			//判断院系名重复
			if(departmentList != null && departmentList.size() != 0){
				failMsg = "该院系名已存在";
			}else{
				//修改院系
				departMentDao.saveDepartment(paramMap);
				result = true;
			}
			if(!result){
				resultMap.put("failMsg", failMsg);
			}
			resultMap.put("result", result);
			logger.info("修改院系参数为："+paramMap.toString());
		} catch (Exception e) {
			logger.error("修改院系异常saveDepartment", e);
			throw e;
		}
		return resultMap;
	}
	
	/**
	 * @description 删除院系
	 * @param  list
	 * @return List 
	 * @throws Exception
	 */
	public Map<String, Object> delDepartments(List<String> list) throws Exception{
		
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			String[] tables = {"profession","relation","sys_user"};
			String[] errMsg = {"专业","课程","人员"};
			Map<String, Object> mapUse ;
			List<Boolean> listMark = new ArrayList<Boolean>();
			List<String> noIds = new ArrayList<String>();
			for(String departmentId : list){
				mapUse = this.getDepartmentDelMark("院系",tables, errMsg, "departmentId", Integer.parseInt(departmentId.toString()));
				if((Boolean)mapUse.get("result")){
					listMark.add(true);
				}else{
					//存放不能删除的院系的id
					noIds.add(departmentId);
				}
			}
			if(list.size() == listMark.size()){
				//执行批量删除
				departMentDao.delDepartments(list);
				result.put("result", true);
			}else{
				result.put("result", false);
				result.put("failMsg", getErrorMsg(noIds, 1, "departmentName","院系"));
			}
			logger.info("删除院系参数为："+list.toString());
		}catch(Exception e){
			logger.error("删除院系异常delDepartments", e);
			e.printStackTrace();
			result.put("result", false);
			return result;
		}
		return result;
	}

	/**
	 * @description 通过院系id名拼接错误信息，将给的错误信息拼接好
	 * @param idList
	 * @param mark  1 院系  2地点
	 * @param columnName
	 * @param chineseName
	 * */
	public String getErrorMsg(List<String> idList, int mark, String columnName, String chineseName){
		List<Map<String, Object>> idMapList = new ArrayList<Map<String, Object>>();
		//院系信息
		if(mark == 1){
			idMapList = departMentDao.getDepartmentByList(idList);
		}else if(mark == 2){
			idMapList = siteDao.getSiteByList(idList);
		}
		//构建参数
		StringBuffer sbuffer = new StringBuffer();
		for(Map<String, Object> map : idMapList){
			sbuffer.append(map.get(columnName).toString()).append("、");
		}
		sbuffer.append(chineseName+"已被使用，无法删除");
		return sbuffer.toString();
	}

	/**
	 * @description 查询院系的专业列表  分页
	 * @param  paramMap Map<String,Object>
	 * @return List 
	 * @throws Exception
	 */
	public Map<String,Object> getDepartmentProfesList(Map<String, Object> paramMap) throws Exception{
		
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try{
			int pageNow = Integer.parseInt(paramMap.get("pageNow").toString());
			int pageSize = Integer.parseInt(paramMap.get("pageSize").toString());
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取列表信息
			List<Map<String, Object>> homeworkList = departMentDao.getDepartmentProfesList(paramMap);
			resultMap.put("professionList", homeworkList);
			resultMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			paramMap.put("startNum", 0);
			List<Map<String, Object>> allList = departMentDao.getDepartmentProfesList(paramMap);
			int totalPage = pageUtil.getTotalPage(allList, pageSize);
			resultMap.put("totalPage", totalPage);
		}catch(Exception e){
			logger.error("查询院系的专业列表异常getDepartmentProfesList", e);
			throw e;
		}
		return resultMap;
	}
	
	/**
	 * @description 查询某个院系是否能删除的标识（也可用于其他数据，需要将数据库表名传进来，还有要判断的字段）
	 * @param useName
	 * @param   tables String[](要查询的表),
	 * @param  errMsg(每个表都是什么表) String[] ,
	 * @param   column（要查询的字段） String,
	 * @param    columnValues（字段值） String
	 * @return List 
	 * @throws Exception
	 */
	public Map<String,Object> getDepartmentDelMark(String useName,String[] tables,String[] errMsg, String column,int columnValues)  {
		
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try{
			resultMap.put("result", true);
			Map<String, Object> paramMap ;
			List<Map<String, Object>> list;
			for(int i = 0; i < tables.length; i++){
				paramMap = new HashMap<String, Object>();
				paramMap.put("tableName", tables[i]);
				paramMap.put("column", column);
				paramMap.put("columnValues", columnValues);
				paramMap.put("delMark", 0);
				list = departMentDao.getMsgList(paramMap);
				if(list != null && list.size() != 0){
					resultMap.put("result", false);
					resultMap.put("errorTitle", tables[i]);
					//resultMap.put("failMsg", errMsg[i]+"还有关联信息不能删除");
					resultMap.put("failMsg", "该"+useName+"下存在"+errMsg[i]+"信息该记录无法删除");
					break;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("工具方法异常getDepartmentDelMark", e);
		}
		return resultMap;
	}
	
	 /**
	 * @description 通过主键查询某院系信息
	 * @param  paramMap Map<String,Object>
	 * @return List 
	 * @throws Exception
	 */
	public Map<String,Object> getDepartmentDetail(Map<String, Object> paramMap) throws Exception{
		
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try{
			resultMap = departMentDao.getDepartmentDetail(paramMap);
		}catch(Exception e){
			logger.error("通过主键查询某院系信息异常getDepartmentDetail", e);
			throw e;
		}
		return resultMap;
	}
	
	 /**
	 * @description 通过某院系id查询下面全部专业信息
	 * @param  paramMap Map<String,Object>
	 * @return List 
	 * @throws Exception
	 */
	public List<Map<String,Object>> getMyProfessionList(Map<String, Object> paramMap) throws Exception{
		
		List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
		try{
			resultList = departMentDao.getMyProfessionList(paramMap);
		}catch(Exception e){
			logger.error("查询某院系下专业异常getMyProfessionList", e);
			throw e;
		}
		return resultList;
	}
}
